import type { MenuProps } from "antd";
import { produce } from "immer";
import { create } from "zustand";
import { persist } from "zustand/middleware"; //用于持久化存储

import { IUserResourceResponse } from "@/api/auth";

type MenuItem = Required<MenuProps>["items"][number];

type Action = {
  updateResource: (value: IUserResourceResponse[]) => void;
  updateMenuList: (menuItem: MenuItem[]) => void;
  updateSelectMenu: (value: string[]) => void;
  updateOpenKeys: (value: string[]) => void;
  updateRoutePath: (value: Path[]) => void;
};

interface Path {
  title: string;
  path: string;
}

interface State {
  resource: IUserResourceResponse[]; // 资源
  menuList: MenuItem[]; // 菜单
  selectMenu: string[]; // 当前选中的菜单
  openKeys: string[]; // 当前展开的菜单
  routePath: Path[];
}

export const usePermissionStore = create<State & Action>()(
  persist(
    //使用持久化组件包裹
    (set) => ({
      resource: [],
      menuList: [],
      selectMenu: [],
      openKeys: [],
      routePath: [],
      updateResource: (value) =>
        set(
          produce((state: State) => {
            state.resource = value;
          })
        ),
      updateMenuList: (value) =>
        set(
          produce((state: State) => {
            state.menuList = value;
          })
        ),
      updateSelectMenu: (value) =>
        set(
          produce((state: State) => {
            state.selectMenu = value;
          })
        ),
      updateOpenKeys: (value) =>
        set(
          produce((state: State) => {
            state.openKeys = value;
          })
        ),
      updateRoutePath: (value) =>
        set(
          produce((state: State) => {
            state.routePath = value;
          })
        ),
    }),
    {
      name: "permission", //在localStorage中对应的key
    }
  )
);
